package concurrecy;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

class Car {

    public synchronized void waxed() {
        notifyAll();
    }

    public synchronized void buffed() {
        notifyAll();
    }

    public synchronized void waitingForWax() throws InterruptedException {
        System.out.println("waiting for wax");
        wait();
    }

    public synchronized void waitingForBuff() throws InterruptedException {
        System.out.println("waiting for buff");
        wait();
    }
}

class WaxOn implements Runnable {
    private Car car;

    public WaxOn(Car car) {
        this.car = car;
    }

    @Override
    public void run() {
        try {
            while (!Thread.interrupted()) {
                TimeUnit.MILLISECONDS.sleep(200);
                car.waxed();
                car.waitingForBuff();
            }
        } catch(InterruptedException e) {
            System.out.println("wax on interrupted");
        }
    }
}

class WaxOff implements Runnable {
    private Car car;

    public WaxOff(Car car) {
        this.car = car;
    }

    @Override
    public void run() {
        try {
            while(!Thread.interrupted()) {
                car.waitingForWax();
                TimeUnit.MILLISECONDS.sleep(300);
                car.buffed();
            }
        } catch(InterruptedException e) {
            System.out.println("wax off interrupted");
        }
    }
}

/**
 * 打蜡 wax
 * 抛光 buff
 * 使用 wait notify
 */
public class WaxDemo {
    public static void main(String[] args) throws InterruptedException {
        Car car = new Car();
        ExecutorService service = Executors.newCachedThreadPool();
        service.execute(new WaxOff(car));
        service.execute(new WaxOn(car));

        TimeUnit.SECONDS.sleep(5);
        service.shutdownNow();
    }
}
